﻿using System.Buffers;
using System.Collections.Generic;
using Xc.DataAccess.Core;
using Xc.DataAccess.Core.Extensions ;
namespace Microsoft.Extensions.DependencyInjection
{
#if NET5_0_OR_GREATER
    public static class SequenceReaderExtensions
    {
        /// <summary>
        /// 读取指定字节长度的数据
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static bool TryRead(ref this SequenceReader<byte> reader, int length, out ReadOnlySequence<byte> dataArea)
        {
            try
            {
                if (reader.UnreadSequence.Length < length)
                {
                    dataArea = ReadOnlySequence<byte>.Empty;
                    return false;
                }
                var data = reader.UnreadSequence.Slice(0, length);
                reader.Advance(length);
                dataArea = data;
                return data.Length == length;

            }
            catch (System.Exception)
            {
                dataArea = ReadOnlySequence<byte>.Empty;
                return false;
            }
        }
        /// <summary>
        /// 尝试读 指定字节的数据
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool TryReadUInt16LittleEndian(ref this SequenceReader<byte> reader, out ushort value)
        {
            if (!reader.TryRead(2, out var contains))
            {
                value = 0;
                return false;
            }
            value = contains.ToArray().ToUInt16LittleEndian();
            return true;
        }
        /// <summary>
        /// 读取为大端数据
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool TryReadUInt16BigEndian(ref this SequenceReader<byte> reader, out ushort value)
        {
            if (!reader.TryRead(2, out var contains))
            {
                value = 0;
                return false;
            }
            value = contains.ToArray().ToUInt16BigEndian();
            return true;
        }
    }
#endif
}
